import {  resources , 
       excelUtil as ExcelUtil
} from '../../../../../../util/';
import {details as DetailsApi ,user as UserApi} from '../../../../../../config/request'
const types = resources.eTypeName;
import echarts from 'echarts';
module.exports = {
    name: 'user_details',
    data() {
        return {
            uid:'',
            user:null,
            integral:'',
            paperMap:null,
            integralData:[],
            progressData:[],
            scoreData:[],
            scoreNames:[],
            papers:[],
            etypes:[],
            paperNames:[],
            answerColumn:null,
            answerOption: {
                title: {
                    text: ''
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data:[],
                    selected: {}
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {},
                        magicType: {
                            show: true,
                            type: ['stack', 'tiled'] // 'bar',
                        },
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: types
                },
                yAxis: {
                    type: 'value'
                },
                series: []
            },
        }
    },
    methods: {
        formatterScore(item) {
            return item.score <= 0 ? item.score : '+' + item.score ;
        },formatterCtime(item) {
            return this.formattertime(item.ctime) ;
        },formattertime(time) {
            return new Date(time * 1000).toLocaleString() ;
        },formatterQtype(qtype) {
            return {
                1:'多选题',
                2:'单选题',
                3:'判断题',
                4:'问答题',
                5:'选择日期',
                6:'选择时间',
                7:'选择数字',
            }[qtype];
        },checkQtype(qtype) {
            return qtype == 1 || qtype == 2;
        },showSorce(option) {
            return option.hasScore ? ' (' + option.score + '分) ' : '';
        },showCheck(option,remark) {
            return option.checked ? ' 选中输入,提示文本为: ' + remark + ' ': '';
        },setOptionColor(vid,oid){
            return Number(vid) == Number(oid) ? 'red' : 'black';
        },
        formatterType(etype){
            return resources.eTypeObj[etype];
        },
        _initScoreData(datas) {

            var that = this;
            var scoreData = [];
            var averageName = '平均分';
            this.etypes.length = 0;
            this.paperNames.length = 0;
            this.scoreNames.length = 0;

            if(datas && datas.length == 0) {
                return
            }
            datas[0].answer.forEach(a => {
                if(a.hasScore) {
                    this.scoreNames.push(a.question.main);
                }
            })
            datas.forEach(data => {
                that.etypes.push(Number(data.etype));
                var answer = { type: that.formatterType(data.etype),ctime : data.time};
                let total = 0;
                let count = 0;
                data.answer.forEach(a => {
                    if(a.hasScore) {
                        answer[a.question.main] = Number(a.scoreOptions[a.valueid].score);
                        count++;
                        total += answer[a.question.main];
                    }
                })
                if(count) {
                    answer[averageName] = total / count;
                }
                scoreData.push(answer);
            })
            this.scoreNames.push(averageName);
            this.scoreData = scoreData;
            this.etypes.sort();
            this.etypes.forEach( etype => {
                that.paperNames.push(that._getPaperNameByEtype(etype));
            })
            this._initColumn();
        },_initColumn() {
            var options = [];
            var indexs = [];
            var that = this;
            var labels = this.scoreNames; 
            var selected = {};
            labels.forEach(select => {
                options.push({
                    name: select,
                    type: 'line',
                    stack: '总分',
                    data: []
                });
                selected[select] = false;   
            }); 
            Object.assign(selected,{"眼红":true,"眼痒":true})
            this.scoreData.forEach(scoreSingle => {
                for (let i = 0, length = labels.length; i < length; i++) {
                    options[i].data.push(scoreSingle[labels[i]]);
                }
            }, this);
            this.answerColumn = echarts.init(document.getElementById('answerColumn'));
            this.answerOption.series = options;
            this.answerOption.xAxis.data = this.paperNames;
            this.answerOption.legend  = {data : labels,selected};
            console.log(this.answerOption)
            this.answerColumn.setOption(this.answerOption);
        },_getPaperNameByEtype(etype){
            return resources.eTypeObj[etype];
        },_initData() {
            this._getPapers()
            this._getIntegral()
            this._getUserInfo()
        },_getPapers() {
            DetailsApi.getAllPapersByUid.call(this, this.uid,data => {
                var scoreData = [];
                var papers = data['papers'];
                console.log("data",data)
                this.papers = papers;
                this._initProgressData(papers);
                papers.forEach(paper => {
                    paper.answer.forEach(a => {
                        a.question.options = JSON.parse(a.question.options);
                        if(a.question.options && a.question.options.length > 0) {
                            a.hasScore = a.question.options[0].hasScore;
                            if(a.hasScore) {
                                a.scoreOptions = {}
                                a.question.options.forEach(option => {
                                    a.scoreOptions[option.id] = option;
                                })
                            }
                        }
                    })
                    if(paper.etype <= 8) {
                        scoreData.push(paper);
                    }
                
                });
                this._initScoreData(scoreData);
            })
        },_getIntegral() {
            DetailsApi.getIntegralByUid.call(this, this.uid,data => {
                this.integralData = data['userIntegrals'];
            })
        },_getUserInfo() {
            UserApi.findUser.call(this,{uid:this.uid},data => {
                this.user = data['user']
            })
        },_initProgressData(papers){
            const paperMap = new Map()
            papers.forEach( paper => {
                paperMap.set(paper.etype,paper)
            })
            this.paperMap = paperMap
            const etypes        = resources.eType
            const progressData  = []
            let   totalProgress = 0
            etypes.forEach(etype => {
                let paper    = paperMap.get(etype.value)
                let progress = 0
                if(paper && paper.answer) {
                    let total    = paper.answer.length
                    let complete = 0
                    paper.answer.forEach(a => {
                        if(a.value) {
                            complete++
                        } 
                    })
                    progress = total / total
                }
                progress *= 100
                totalProgress += progress
                progress = Math.round(progress)
                progress += "%"
                progressData.push({
                   type: etype.key,progress:progress
                })
            })
            totalProgress /= etypes.length
            totalProgress = Math.round(totalProgress)
            totalProgress += "%"
            progressData.push({
                   type: "总进度",progress:totalProgress
                })
            this.progressData = progressData
        },getUserInfo() {
            var user = this.user
            if(!user) {
                return []
            } 
            var datas = []
            var fides = [
                {key:"name",value:"姓名"},
                {key:"nickName",value:"昵称"},
                {key:"sex",value:"性别",format:sex => sex == 1 ? '男' : '女'},
                {key:"phone",value:"手机号"},
                {key:"age",value:"年龄"},
                {key:"address",value:"住址"},
            ]
            fides.forEach(fide => {
                if(user[fide.key]) {
                    let value = user[fide.key]
                    if(fide.format) {
                        value = fide.format(value)
                    }
                    datas.push({
                        key:fide.value,
                        value
                    })
                }
            })
            return datas
        },downloadExl() {
            this.downloadName = '用户-' + this.user.name + '-信息-' + new Date().getTime() + '.xlsx';
            var tableData = this.progressData;
            var data = ExcelUtil.formatterData(tableData, [],{'type':'问卷类型','progress':'答题进度'});
            console.log(data,this.user)
            this.generateExl(this.downloadName, this._generateData());
        },_generateData() {
            const tableHead = ["姓名","昵称","性别","手机号","地址","积分","加入时间","医生姓名"," ","  ","   ","    ","     "]
            const user = this._getUserData(tableHead)
            const progress = this._getProgressData(tableHead)
            const paper = this._getPaperData(tableHead)
            return [user,...progress,...paper]
        },_getUserData(tableHead){
            const obj = {}
            const user = this.user
            obj[tableHead[0]] = user.name
            obj[tableHead[1]] = user.nickName
            obj[tableHead[2]] = user.sex == 1 ? '男' : '女'
            obj[tableHead[3]] = user.phone
            obj[tableHead[4]] = user.address
            obj[tableHead[5]] = user.integral 
            obj[tableHead[6]] = user.createdAt.replace("T",' ')
            obj[tableHead[7]] = '李**医生'
            obj[tableHead[8]] = ''
            obj[tableHead[9]] = ''
            obj[tableHead[10]] = ''
            obj[tableHead[11]] = ''
            return obj 
        },_getProgressData(tableHead) {
            const obj_head = {},obj = {}
            const progressData = this.progressData
            obj_head[tableHead[0]] = progressData[0]['type']
            obj_head[tableHead[1]] = progressData[1]['type']
            obj_head[tableHead[2]] = progressData[2]['type']
            obj_head[tableHead[3]] = progressData[3]['type']
            obj_head[tableHead[4]] = progressData[4]['type']
            obj_head[tableHead[5]] = progressData[5]['type']
            obj_head[tableHead[6]] = progressData[6]['type']
            obj_head[tableHead[7]] = progressData[7]['type']
            obj_head[tableHead[8]] = progressData[8]['type']
            obj_head[tableHead[9]] = progressData[9]['type']
            obj_head[tableHead[10]]= progressData[10]['type']
            obj_head[tableHead[11]]= progressData[11]['type']

            obj[tableHead[0]] = progressData[0]['progress']
            obj[tableHead[1]] = progressData[1]['progress']
            obj[tableHead[2]] = progressData[2]['progress']
            obj[tableHead[3]] = progressData[3]['progress']
            obj[tableHead[4]] = progressData[4]['progress']
            obj[tableHead[5]] = progressData[5]['progress']
            obj[tableHead[6]] = progressData[6]['progress']
            obj[tableHead[7]] = progressData[7]['progress']
            obj[tableHead[8]] = progressData[8]['progress']
            obj[tableHead[9]] = progressData[9]['progress']
            obj[tableHead[10]]= progressData[10]['progress']
            obj[tableHead[11]]= progressData[11]['progress']
            return [obj_head ,obj]
        },_getPaperData(tableHead) {
            const etypes = resources.eType
            const paperMap = this.paperMap
            // let length = 0
            // etypes.forEach(etype => {
            //     let paper    = paperMap.get(etype.value)
            //     if(paper && paper.answer && length < paper.answer.length) {
            //         length = paper.answer.length
            //     }
            // })
            const data = []
            for(let i = 0 ; i < etypes.length ; i++) {
                let etype    = etypes[i]
                let paper    = paperMap.get(etype.value)
                if( paper && paper.answer) {
                    for(let j = 0 ; j < paper.answer.length ; j++) {
                        let answer = paper.answer[j]
                        let content = `问：${answer.question.main}   答：${answer.value}`
                        if(!data[j]) {
                           data[j] = []
                        }
                        data[j][tableHead[i]] = content
                    }
                } 
            }
           return data
        },
        generateExl(name, data) {
            ExcelUtil.downloadExl(name, data);
        },
    },
    created : function() {
        var that = this;
        if(this.$route.query) {
            this.uid = this.$route.query.uid;
            this.integral = this.$route.query.integral;
        }
        this._initData()
    }
}